package org.jfk.core.utils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

public class JsonUtil {
	/**
	 * 
	 * 函数名称: parseData 函数描述: 将json字符串转换为map
	 * 
	 * @param data
	 * @return
	 */
	public static Map<String, String> jsonToMap(String data) {
		GsonBuilder gb = new GsonBuilder();
		Gson g = gb.create();
		Map<String, String> map = g.fromJson(data,
				new TypeToken<Map<String, Map>>() {
				}.getType());
		return map;
	}

	/**
	 * 
	 * 函数名称: jsonToMap2 函数描述: 将json字符串转换为map
	 * 
	 * @param data
	 * @return
	 */
	public static Map<String, Object> jsonToMap2(String data) {
		GsonBuilder gb = new GsonBuilder();
		Gson g = gb.create();
		Map<String, Object> map = g.fromJson(data,
				new TypeToken<Map<String, Object>>() {
				}.getType());
		
		return map;
	}
	
	
	public static List jsonToList(String data){
		GsonBuilder gb = new GsonBuilder();
		Gson gson = gb.create();		
		ArrayList list = new ArrayList();
		Type listType = new TypeToken() {}.getType();
		list = gson.fromJson(data, listType); 		
		return list;
	}
	
    public static <T> List<T> jsonToList(String json, Class<T[]> clazz)
    {
        Gson gson = new Gson();
        T[] array = gson.fromJson(json, clazz);
        return Arrays.asList(array);
    }
    
    public static <T> ArrayList<T> jsonToArrayList(String json, Class<T> clazz)
    {
        Type type = new TypeToken<ArrayList<JsonObject>>()
        {}.getType();
        ArrayList<JsonObject> jsonObjects = new Gson().fromJson(json, type);

        ArrayList<T> arrayList = new ArrayList<>();
        for (JsonObject jsonObject : jsonObjects)
        {
            arrayList.add(new Gson().fromJson(jsonObject, clazz));
        }
        return arrayList;
    }
    
    public static JsonObject json2Object(String data){
    	Gson gson = new Gson();
    	return gson.fromJson(data, JsonObject.class);
    }
    
    public static JsonArray json2Array(String data){
    	Gson gson = new Gson();
    	return gson.fromJson(data, JsonArray.class);
    }   	
	
	public static String map2jsonStr(Map m){
		Gson gson = new Gson();
		 String jsonStr = gson.toJson(m);
		 return jsonStr;		
	}
}
